<template>
  <div class="page-miH page-bgBack">
    <a-spin :spinning="loading">
      <div class="pageStyle">
        <div class="page-miH" style="min-width: 250px; width: 250px; border-right: 1px solid #e8e8e8">
          <div class="leftBox">
            <div class="searchBox">
              <div class="titleStyle">租户列表</div>
              <div class="addIcon">
                <a-icon type="plus" @click="showSiteAll" />
              </div>
            </div>
            <a-input-search placeholder="请输入" style="margin-top: 12px" @search="onSearch" v-model="selectSiteName" />
            <div class="siteBox">
              <div
                @click="siteChange(item, index)"
                :class="item.isSelected ? 'sitemItemOn' : 'sitemItem'"
                v-for="(item, index) in siteList"
                :key="index"
              >
                <a-tooltip>
                  <template slot="title">
                    {{ item.customerName }}
                  </template>
                  <div class="planTitle" style="width: 180px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
                    {{ item.customerName }}
                  </div>
                </a-tooltip>
                <a-popconfirm
                  :title="`确定要将租户${item.customerName}在列表中移除吗`"
                  cancelText="取消"
                  okText="确定"
                  @confirm.stop="deleleSite(item)"
                >
                  <a-icon type="delete" @click.stop />
                </a-popconfirm>
              </div>
            </div>
            <a-pagination
              style="margin-right: 0px; margin-top: 24px"
              v-model="current"
              :pageSize="10"
              :total="total"
              @change="onPageChange"
            />
          </div>
        </div>
        <employee-select
          :show.sync="visibleForSite"
          :default-selected-keys="selectedSiteList"
          :selected-list.sync="selectedSiteList"
          @change="onEmployeeSelectChange"
        />
        <div class="rightBox">
          <div class="functionBtn">
            <a-button :disabled="!siteList.length" type="primary" @click="addPlan">新增投保方案</a-button>
          </div>
          <div class="planBox" v-if="planList && planList.length">
            <div class="planItem" v-for="(item, index) in planList" :key="index">
              <a-dropdown>
                <a-menu slot="overlay" @click="(e) => handleMenuClick(e, item)">
                  <a-menu-item key="1">编辑</a-menu-item>
                  <a-menu-item key="2">删除</a-menu-item>
                </a-menu>
                <a-icon type="ellipsis" class="funcBtn" />
              </a-dropdown>
              <div class="contentBox">
                <a-tooltip>
                  <template slot="title">
                    {{ item.schemeName }}
                  </template>
                  <div class="planTitle" style="width: 180px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
                    {{ item.schemeName }}
                  </div>
                </a-tooltip>
                <div class="planContent">
                  <div class="planKey">投保公司：</div>
                  <div class="planValue">{{ item.companyName }}</div>
                </div>
                <div class="planContent" style="display: flex; align-items: center">
                  <div class="planKey">方案明细:</div>
                  <a-popover placement="bottomLeft" title="方案明细">
                    <template slot="content">
                      <div style="display: flex; width: 540px; flex-wrap: wrap">
                        <div
                          style="
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            padding: 0 16px;
                            margin: 12px 12px 0 0;
                            width: 254px;
                            height: 41px;
                            background: #f6f6f6;
                            border-radius: 4px;
                          "
                          v-for="(item, index) in item.personTypeList"
                          :key="index"
                        >
                          <a-tooltip>
                            <template slot="title">
                              {{ item.typeName }}
                            </template>
                            <div
                              style="
                                font-size: 14px;
                                font-weight: 500;
                                color: #55565d;
                                width: 98px;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                                overflow: hidden;
                              "
                            >
                              {{ item.typeName }}
                            </div>
                          </a-tooltip>
                          <div>
                            <span class="label">保险月费：</span>
                            <span class="value">{{ item.monthAmount }}</span>
                          </div>
                        </div>
                      </div>
                    </template>
                    <a-button type="link">查看</a-button>
                  </a-popover>
                </div>
                <div class="planContent">
                  <div class="planKey">方案确认函：</div>
                  <a-tooltip>
                    <template slot="title">
                      <div>{{ item.remark }}</div>
                    </template>
                    <div style="width: 120px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden" class="planValue">
                      {{ item.remark }}
                    </div>
                  </a-tooltip>
                </div>
              </div>
            </div>
          </div>
          <div v-else style="padding: 120px 40%">
            <a-empty />
          </div>
        </div>
        <a-modal :title="title" v-model="visible" :width="660" @ok="handelOk" @cancel="visible = false">
          <div class="modalContent">
            <div class="itemContent">
              <div class="itemTitle"><span style="color: #fa5051">*</span>投保公司</div>
              <a-select
                allowClear
                placeholder="请选择"
                v-model="planItem.insCompanyId"
                style="width: 300px; margin-left: 24px"
                @change="insuranceChange"
              >
                <a-select-option v-for="(item, index) in insuranceList" :key="index" :value="item.insCompanyId">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </div>
            <div class="itemContent">
              <div class="itemTitle"><span style="color: #fa5051">*</span>投保方案</div>
              <a-select
                allowClear
                placeholder="请选择"
                @change="selectPlan"
                v-model="selectPlanItem"
                style="width: 300px; margin-left: 24px"
              >
                <a-select-option v-for="(item, index) in selectPlanList" :key="index" :value="item.id">
                  {{ item.schemeName }}
                </a-select-option>
              </a-select>
            </div>
            <div class="itemContent">
              <div class="itemTitle">方案确认函</div>
              <a-upload
                ref="upload"
                :file-list="fileList"
                :headers="headers"
                action="/file/api/v1/general/upload/attachment"
                @change="handleChange"
                name="files"
                :showUploadList="{
                  showDownloadIcon: true
                }"
                @download="download"
                style="margin-left: 24px; display: flex"
              >
                <a-button>
                  <a-icon type="plus" />
                  {{ !fileList.length ? "上传文件" : "重新上传" }}
                </a-button>
              </a-upload>
              <!-- <a-button style="margin-left: 24px">添加附件</a-button> -->
            </div>
            <div v-if="realityMonthAmount" style="margin-top: 12px">
              <div
                style="
                  padding: 0 36px;
                  width: 526px;
                  height: 48px;
                  background: #fafafa;
                  box-shadow: inset 0px -1px 0px 0px #e8e8e8;
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                "
              >
                <div style="font-size: 14px; font-weight: 500; color: #252525">职业分类</div>
                <div style="margin-left: 60px; font-size: 14px; font-weight: 500; color: #252525">实际保险月费</div>
                <div style="margin-left: 52px; font-size: 14px; font-weight: 500; color: #252525">
                  <span style="color: #fa5051">*</span>保险月费<span
                    style="font-size: 12px; font-weight: 400; color: #a6a8b4; margin-left: 16px"
                    >京普给人资公司的价格</span
                  >
                </div>
              </div>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: flex-start;
                  width: 526px;
                  height: 48px;
                  background: #ffffff;
                  box-shadow: inset 0px -1px 0px 0px #e8e8e8;
                "
                v-for="(item, index) in realityMonthAmount"
                :key="index"
              >
                <a-tooltip>
                  <template slot="title">
                    <div>{{ item.typeName }}</div>
                  </template>
                  <div
                    style="width: 120px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; margin-left: 36px"
                    class="value"
                  >
                    {{ item.typeName }}
                  </div>
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <div>{{ item.realityMonthAmount }}</div>
                  </template>
                  <div style="width: 120px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden" class="value">
                    {{ item.realityMonthAmount }}
                  </div>
                </a-tooltip>
                <a-input-number v-model="item.monthAmount" placeholder="请输入" style="width: 180px; margin-left: 16px" />
              </div>
            </div>
          </div>
        </a-modal>
      </div>
    </a-spin>
  </div>
</template>

<script>
import {
  bachSaveCustomer,
  selectSite,
  deleleSite,
  selectSiteWithInsurance,
  getPlan,
  addPlanForSite,
  editPlanForSite,
  getPlanList,
  selectCompanyBySiteId,
  deletePlan
} from "./api";
import { publicDownLoad } from "../downLoad";
import { getToken } from "xqjr-module-auth";
export default {
  components: {
    EmployeeSelect: () => import("./selectSite.vue")
  },
  data() {
    return {
      siteList: [],
      planList: [],
      visible: false,
      visibleForSite: false,
      selectPlanItem: undefined,
      selectSiteName: undefined,
      title: "新增投保方案",
      loading: false,
      planItem: {},
      companyDetail: {},
      selectedSiteList: [],
      realityMonthAmount: null,
      current: 1,
      total: 0,
      insuranceList: [],
      selectPlanList: [],
      fileList: [],
      selectedSite: {},
      headers: {}
    };
  },
  watch: {
    visible(val) {
      if (val === false) {
        this.getPlanList();
      }
    }
  },
  created() {
    this.selectSite();
    this.getSiteList();
    this.headers = {
      token: getToken()
    };
  },
  methods: {
    download(file) {
      if (file.url) {
        publicDownLoad(file.url);
      } else if (file.response.data && file.response.data[0]) {
        publicDownLoad(file.response.data[0]);
      } else {
        this.$message.warning("文件下载失败");
      }
    },
    // 新增编辑投保方案-保存
    handelOk() {
      var haAmount = true;
      var isZero = true;
      if (this.realityMonthAmount && this.realityMonthAmount.length) {
        this.realityMonthAmount.forEach((item) => {
          if (!item.monthAmount && item.monthAmount !== 0) {
            haAmount = false;
          } else if (item.monthAmount === 0) {
            isZero = false;
          }
        });
      }
      if (!this.planItem.insCompanyId) {
        this.$message.warning("投保公司必选");
      } else if (!this.selectPlanItem) {
        this.$message.warning("投保方案必选");
      } else if (!haAmount) {
        this.$message.warning("保险月费必填");
      } else if (!isZero) {
        this.$message.warning("保险月费不能为0");
      } else {
        var selectPlanItemName = "";
        this.selectPlanList.forEach((item) => {
          if (item.id === this.selectPlanItem) {
            selectPlanItemName = item.schemeName;
          }
        });
        // var companyName = "";
        // this.insuranceList.forEach((item) => {
        //   if (item.id === this.planItem.insCompanyId) {
        //     companyName = item.name;
        //   }
        // });
        var arr = {
          ...this.planItem,
          schemeId: this.selectPlanItem,
          customerId: this.selectedSite.id,
          companyName: this.companyDetail.companyName,
          schemeName: selectPlanItemName,
          insCompanyId: this.companyDetail.id,
          personTypeList: this.realityMonthAmount
        };
        if (this.title === "新增投保方案") {
          addPlanForSite(arr).then((res) => {
            this.visible = false;
            this.getPlanList();
            this.$message.success("保存成功");
          });
        } else if (this.title === "编辑投保方案") {
          editPlanForSite(arr).then((res) => {
            this.visible = false;
            this.getPlanList();
            this.$message.success("保存成功");
          });
        }
      }
    },
    // 方案确认函
    handleChange(info) {
      let fileList = [...info.fileList];
      fileList = fileList.slice(-1);
      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
      this.fileList = fileList;
      if (this.fileList && this.fileList.length) {
        if (this.fileList[0].status === "done" && this.fileList[0].response.data && this.fileList[0].response.data[0]) {
          this.planItem.schemeConfirmFile = this.fileList[0].response.data[0];
          this.planItem.remark = this.fileList[0].name;
        }
      } else {
        this.planItem.schemeConfirmFile = "";
        this.planItem.remark = "";
      }
    },
    // 左侧列表选中变化
    siteChange(item, index) {
      this.siteList.forEach((e, idx) => {
        if (idx === index) {
          e.isSelected = true;
          this.selectedSite = e;
          this.getPlanList();
        } else {
          e.isSelected = false;
        }
      });
      this.siteList = JSON.parse(JSON.stringify(this.siteList));
    },
    // 查询右侧方案列表
    getPlanList() {
      this.loading = true;
      getPlanList({
        customerId: this.selectedSite.id
      })
        .then((res) => {
          this.planList = res.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 新增编辑投保方案-选择保险公司变化
    insuranceChange(e) {
      this.selectPlanItem = undefined;
      this.realityMonthAmount = null;
      if (e) {
        selectCompanyBySiteId(e).then((res) => {
          this.companyDetail = res.data;
          if (res.data.id) {
            getPlan(res.data.id, this.selectedSite.id, { schemeId: this.selectPlanItem ? this.selectPlanItem : undefined }).then((res) => {
              this.selectPlanList = res.data;
            });
          }
        });
      } else {
        this.selectPlanList = [];
      }
    },
    // 新增编辑投保方案-选择参保方案变化
    selectPlan(e) {
      if (e) {
        this.selectPlanList.forEach((item) => {
          if (item.id === e) {
            this.realityMonthAmount = item.personTypeList;
          }
        });
      } else {
        this.realityMonthAmount = null;
      }
    },
    // 查询保险公司列表
    getSiteList() {
      selectSiteWithInsurance()
        .then((res) => {
          this.insuranceList = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 列表中移除已经添加的租户
    deleleSite(item) {
      deleleSite(item.id).then((res) => {
        this.$message.success("删除成功");
        this.selectSite();
      });
    },
    // 左侧分页
    onPageChange() {
      this.selectSite();
    },
    // 查询左侧租户列表
    selectSite() {
      selectSite({ pageSize: 10, pageNo: this.current, siteName: this.selectSiteName })
        .then((res) => {
          if (res.data.entities.length === 0 && this.current > 1) {
            // 当本页非第一页（比第一页大）时，删除最后一条后台会返回当页页码，
            // 但是本页数据为空，table组件会展示为当前页的上一页数据为空，需要加加判断再拉一下上页数据
            this.current = this.current - 1;
            this.pageSize = 10;
            this.selectSite();
          } else {
            this.siteList = res.data.entities;
            this.total = res.data.entityCount;
            if (this.siteList.length) {
              this.siteList[0].isSelected = true;
              this.selectedSite = this.siteList[0];
              this.getPlanList();
            } else {
              this.planList = [];
              this.loading = false;
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 租户筛选框变化
    onEmployeeSelectChange(list) {
      var arr = [];
      list.forEach((item) => {
        arr.push({ siteId: item.id, siteName: item.name });
      });
      bachSaveCustomer({ bachSaveCustomerList: arr })
        .then((res) => {
          this.$message.success("保存成功");
          this.visibleForSite = false;
          this.selectSite();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 租户筛选框弹出
    showSiteAll() {
      this.visibleForSite = true;
      this.selectedSiteList = [];
    },
    addPlan() {
      this.visible = true;
      this.title = "新增投保方案";
      this.planItem = {};
      this.fileList = [];
      this.selectPlanItem = undefined;
      this.realityMonthAmount = null;
      this.selectPlanList = [];
    },
    // 左侧搜索
    onSearch() {
      this.current = 1;
      this.selectSite();
    },
    // 右侧方案编辑删除
    handleMenuClick(e, item) {
      if (e.key === "1") {
        this.visible = true;
        this.title = "编辑投保方案";
        this.fileList = [];
        this.realityMonthAmount = null;
        selectCompanyBySiteId(item.insCompanyId).then((response) => {
          this.companyDetail = response.data;
          getPlan(this.companyDetail.id, this.selectedSite.id, { schemeId: item.schemeId ? item.schemeId : undefined }).then((res) => {
            this.selectPlanList = res.data;
            // this.selectPlanList.forEach((i) => {
            //   if (i.id === item.schemeId) {
            //     this.realityMonthAmount = i.personTypeList;
            //   }
            // });
          });
        });
        this.realityMonthAmount = item.personTypeList;
        this.planItem = {
          insCompanyId: item.insCompanyId,
          schemeConfirmFile: item.schemeConfirmFile,
          remark: item.remark,
          id: item.id
        };
        if (item.remark && item.schemeConfirmFile) {
          this.fileList = [
            {
              uid: "1",
              name: item.remark,
              status: "done",
              response: "Server Error 500",
              url: item.schemeConfirmFile
            }
          ];
        }
        this.selectPlanItem = item.schemeId;
      } else if (e.key === "2") {
        var that = this;
        this.$confirm({
          title: "确定删除此投保方案吗?",
          content: (h) => <div style="color:red;">{item.schemeName}</div>,
          onOk() {
            deletePlan(item.id).then((res) => {
              that.$message.success("删除成功");
              that.getPlanList();
            });
          },
          onCancel() {
            console.log("Cancel");
          },
          class: "test"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep.ant-upload-list {
  width: 100% !important;
}
::v-deep .ant-upload-list-item {
  width: 330px;
  .ant-upload-list-item-name {
    width: 270px;
  }
}
.label {
  height: 14px;
  font-size: 14px;
  font-weight: 400;
  color: #a6a8b4;
}
.value {
  font-size: 14px;
  font-weight: 400;
  color: #636572;
}
.pageStyle {
  padding: 24px 0;
  display: flex;
}
.addIcon {
  cursor: pointer;
  color: var(--primary);
}
.leftBox {
  padding: 12px 24px;
  .searchBox {
    display: flex;
    justify-content: space-between;
    .titleStyle {
      font-size: 16px;
      font-weight: 500;
      color: #252525;
    }
  }
  .siteBox {
    margin-top: 8px;
    .sitemItem {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
      padding: 0 12px;
      font-size: 14px;
      font-weight: 400;
      border-bottom: 1px solid #e8e8e8;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .sitemItem:hover {
      background-color: var(--primary10);
      border-bottom: none;
    }
    .sitemItemOn {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
      padding: 0 12px;
      font-size: 14px;
      font-weight: 400;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: var(--primary10);
      border-bottom: none;
    }
  }
}
.modalContent {
  padding: 16px 0 16px 60px;
  .itemContent {
    display: flex;
    align-items: center;
    margin-top: 24px;
    .itemTitle {
      font-size: 14px;
      font-weight: 400;
    }
  }
}
.rightBox {
  width: 100%;
  .functionBtn {
    display: flex;
    justify-content: flex-start;
    margin-left: 32px;
  }
  .planBox {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .planItem {
      width: 30%;
      height: 146px;
      border-radius: 3px;
      border: 1px solid #e8e8e8;
      position: relative;
      margin-left: 32px;
      margin-top: 24px;
      .funcBtn {
        cursor: pointer;
        position: absolute;
        top: 0;
        right: 0;
        font-size: 18px;
        margin-top: 12px;
        margin-right: 12px;
      }
      .contentBox {
        margin-top: 24px;
        margin-left: 18px;
        .planTitle {
          font-size: 14px;
          font-weight: 500;
          color: #3c3d43;
        }
        .planContent {
          display: flex;
          margin-top: 4px;
          .planKey {
            font-size: 14px;
            font-weight: 400;
            color: #a6a8b4;
          }
          .planValue {
            font-size: 14px;
            font-weight: 400;
            color: #636572;
          }
        }
      }
    }
  }
}
</style>
